package com.train.rabbitmq01api.api.message;

import java.util.HashMap;
import java.util.Map;

import com.rabbitmq.client.*;
import com.train.rabbitmq01api.consumer.MyConsumer;

public class Consumer {

	public static void main(String[] args) throws Exception {
		
		//1 创建一个ConnectionFactory, 并进行配置
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost("192.168.13.128");
		connectionFactory.setPort(5672);
		connectionFactory.setVirtualHost("/");
		
		//2 通过连接工厂创建连接
		Connection connection = connectionFactory.newConnection();
		
		//3 通过connection创建一个Channel
		Channel channel = connection.createChannel();
		
		//4 声明（创建）一个队列
		String queueName = "test001";

		// 视频3_11 TTL消息详解
		//设置队列的过期时间10s
		Map<String,Object> param = new HashMap<>();
		param.put("x-message-ttl", 10000); // 注意这里是针对队列设置消息的过期时间为10s
		channel.queueDeclare(queueName, true, false, false, param);

		//5 创建消费者(需要创建一个DefaultConsumer的子类)
		DefaultConsumer queueingConsumer = new MyConsumer(channel);

		//6 设置Channel
		// 参数 1 queue 要消费的队列  2 autoAck 是否自动签收,true的话消费端会回送给mq一个ack消息  3 callback  具体的消费者对象
		channel.basicConsume(queueName, true, queueingConsumer);

		// 7 获取消息 放到MyConsumer的handleDelivery实现方法内
//		while(true){
//			//7 获取消息
//			Delivery delivery = queueingConsumer.nextDelivery();
//			String msg = new String(delivery.getBody());
//			System.err.println("消费端: " + msg);
//			Map<String, Object> headers = delivery.getProperties().getHeaders();
//			System.err.println("headers get my1 value: " + headers.get("my1"));
//
//			//Envelope envelope = delivery.getEnvelope();
//		}
		
	}
}
